package org.demo.swt;


import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.resource.FontRegistry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

/**
 * 
 * @author  
 * @date    2010-10-21
 * @file    org.demo.swt.SWTHelloWorld.java
 */
public class SWTHelloWorld {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final Display display = new Display();
		Shell shell = new Shell(display);
		// 
		shell.setText("Hello World");
		shell.setBounds(400, 200, 600, 300);
		shell.setLayout(new FillLayout());
		// 
		processMonitor(shell);
		// 
		shell.open();
		while(!shell.isDisposed()){
			if (!display.readAndDispatch()){
				display.sleep();
			}
		}
		display.dispose();		
	}
	
	private static void tree(final Shell shell){
		final Tree tree = new Tree(shell,SWT.SINGLE);
		for (int i=0; i<3; ++i){
			TreeItem parent = new TreeItem(tree,SWT.NULL);
			parent.setText("parent - " + i);
			for (int j=0; j<3; ++j){
				TreeItem child = new TreeItem(parent,SWT.NULL);
				child.setText("child - " + j);
			}
		}
		tree.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				TreeItem[] items = tree.getSelection();
				if (items.length > 0){
					System.out.println(items[0].getText());
				}
			    items[0].setForeground(new Color(shell.getDisplay(),0,255,0));
			    items[0].setBackground(new Color(shell.getDisplay(),223,232,246));
			}
		});
	}
	private static void processMonitor(Shell shell){
		ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
		try {
			dialog.run(true, true, new IRunnableWithProgress() {
				public void run(IProgressMonitor monitor)
						throws InvocationTargetException, InterruptedException {
					final int ticks = 10000;
					monitor.beginTask("开始操作", ticks);
					try {
						for (int i=0; i<ticks; i++){
							if (monitor.isCanceled()){
								throw new InterruptedException();
							}
							monitor.worked(1);
						}
					} finally {
						monitor.done();
					}
				}
			});
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
